<?php
declare (strict_types = 1);

namespace app\middleware;

use app\model\AdminRolePermission;
use think\facade\Session;
use think\Validate;

class AdminRolePermissionMiddleware
{
    public function handle($request, \Closure $next)
    {
        // admin_menu.uri = admin/config/index，这是表里保存的记录结构,要去掉左右两边的 "/"
        try {
            $uri = trim($request->baseUrl(), '/');
        } catch (\Exception $e){
            $uri = 'admin';
        }

        // 验证访问路由 uri 的格式
        $data    = ['uri' => $uri];
        $rules   = ['uri' => 'max:255|regex:^[A-Za-z0-9\/\_\-\#]+$'];
        $message = [
            'uri.max'   => 'url 长度不能超过 255',
            'uri.regex' => 'url 只能是字母、数字、正斜杠/、下划线_、破折号-、井号#',
        ];
        $validate = new Validate;
        $validate->message($message);
        if ($validate->check($data, $rules) === false) return json(['code' => 0, 'message' => $validate->getError()], 200);

        // 在 config/super_admin.php 配置文件里的账户将跳过以下校验
        if (in_array(Session::get('admin_user.account'), config('super_admin'))) goto JUMP;

        $admin_role_id = Session::get('admin_user.admin_role_id') ?? 0;
        if (1 > $admin_role_id) return json(['code' => 0, 'message' => '无访问权限']);

        // 判断角色权限 id 是否有访问权限
        if (AdminRolePermission::isPass($admin_role_id, $uri) === false) return json(['code' => 0, 'message' => '无访问权限']);

        JUMP:
        return $next($request);
    }
}
